package com.lottery.im.module.result.ui.statistics;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.GridView;
import butterknife.BindView;
import butterknife.OnClick;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.BallChooseInfo;
import com.lottery.im.api.result.entity.GameHistoryInfo;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.constant.Constants;
import com.lottery.im.constant.RxBusCode;
import com.lottery.im.module.result.adapter.result.statistics.BallChooseAdapter;
import com.lottery.im.module.result.adapter.result.statistics.History115Adapter;
import com.lottery.im.module.result.adapter.result.statistics.HistoryLotteryAdapter;
import com.lottery.im.module.result.adapter.result.statistics.HistoryPkAdapter;
import com.lottery.im.module.result.presenter.WinStatisticsPresenter;
import com.lottery.im.module.result.view.WinStatisticsView;
import com.lottery.im.util.rxbus.RxBus;
import com.lottery.im.util.rxbus.Subscribe;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 号码分布
 */
public class BallStatisticsFragment extends BaseSwipeFragment<WinStatisticsPresenter>
    implements WinStatisticsView {
  private final static String GAME_TYPE_KEY = "GAME_TYPE_KEY";

  public static BallStatisticsFragment create(String gameType) {
    BallStatisticsFragment fragment = new BallStatisticsFragment();
    Bundle b = new Bundle();
    b.putString(GAME_TYPE_KEY, gameType);
    fragment.setArguments(b);
    return fragment;
  }

  @BindView(R.id.refreshLayout) RefreshLayout mRefreshLayout;
  @BindView(R.id.history_list) RecyclerView mRecyclerView;
  @BindView(R.id.ball_list) GridView mBallRecyclerView;
  @BindView(R.id.cb_choose_big) CheckBox mCbBig;
  @BindView(R.id.cb_choose_small) CheckBox mCbSmall;
  @BindView(R.id.cb_choose_single) CheckBox mCbSingle;
  @BindView(R.id.cb_choose_double) CheckBox mCbDouble;
  private List<GameHistoryInfo> mHistoryList = new ArrayList<>();
  private List<BallChooseInfo> mBallList = new ArrayList<>();
  private List<String> allItems = new ArrayList<>();
  private List<String> items = new ArrayList<>();
  private HistoryPkAdapter mPkAdapter;
  private History115Adapter m115Adapter;
  private HistoryLotteryAdapter mAdapter;
  private BallChooseAdapter mBallChooseAdapter;
  private boolean isBig, isSmall, isSingle, isDouble;
  private String mGameType = "";
  private int startRow = 0;
  private int pageSize = 30;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_statistics_ball;
  }

  @Override protected void initPresenter() {
    presenter = new WinStatisticsPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    if (getArguments() == null) {
      popBackStack();
      return;
    } else {
      RxBus.get().register(this);
      mGameType = getArguments().getString(GAME_TYPE_KEY);
      mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

      if (Constants.pkArr.contains(mGameType)) {
        mPkAdapter = new HistoryPkAdapter(mHistoryList);
        mRecyclerView.setAdapter(mPkAdapter);
        for (int i = 1; i < 11; i++) {
          allItems.add(i + "");
          BallChooseInfo info = new BallChooseInfo(i + "", false);
          mBallList.add(info);
        }
        mBallRecyclerView.setNumColumns(10);
      } else if (Constants.sd115Arr.contains(mGameType)) {
        m115Adapter = new History115Adapter(mHistoryList);
        mRecyclerView.setAdapter(m115Adapter);
        for (int i = 1; i < 12; i++) {
          allItems.add(i < 10 ? ("0" + i) : i + "");
          BallChooseInfo info = new BallChooseInfo(i + "", false);
          mBallList.add(info);
        }
        mBallRecyclerView.setNumColumns(11);
      } else {
        mAdapter = new HistoryLotteryAdapter(mHistoryList);
        mRecyclerView.setAdapter(mAdapter);
        for (int i = 0; i < 10; i++) {
          allItems.add(i + "");
          BallChooseInfo info = new BallChooseInfo(i + "", false);
          mBallList.add(info);
        }
        mBallRecyclerView.setNumColumns(10);
      }
      mBallChooseAdapter = new BallChooseAdapter(mBallList, getActivity());
      mBallRecyclerView.setAdapter(mBallChooseAdapter);
      mBallChooseAdapter.setOnBallClickListener((position, isSelect) -> {
        items.clear();
        for (int i = 0; i < mBallList.size(); i++) {
          if (i == position) {
            if (mBallList.get(i).isSelect()) {
              mBallList.get(i).setSelect(false);
              items.addAll(allItems);
            } else {
              mBallList.get(i).setSelect(true);
              items.add(allItems.get(i));
            }
          } else {
            mBallList.get(i).setSelect(false);
          }
        }
        if (null != mPkAdapter) {
          mPkAdapter.setAlpha(items);
        }
        if (null != m115Adapter) {
          m115Adapter.setAlpha(items);
        }
        if (null != mAdapter) {
          mAdapter.setAlpha(items);
        }
        mBallChooseAdapter.notifyDataSetChanged();
        isBig = false;
        isSmall = false;
        isSingle = false;
        isDouble = false;
        mCbBig.setChecked(false);
        mCbSmall.setChecked(false);
        mCbSingle.setChecked(false);
        mCbDouble.setChecked(false);
      });
      RecyclerViewDivider.with(mActivity)
          .color(ContextCompat.getColor(mActivity, R.color.windowBackground))
          .size((int) mActivity.getResources().getDimension(R.dimen.line_size_dp1))
          .hideLastDivider()
          .build()
          .addTo(mRecyclerView);
      mRefreshLayout.setOnRefreshListener(refreshLayout -> {
        refreshLayout.finishRefresh(1000);
        startRow = 0;
        presenter.queryGameTypeResult(mGameType, startRow, pageSize);
      });
      mRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
        refreshLayout.finishLoadMore(0);
        startRow += pageSize;
        presenter.queryGameTypeResult(mGameType, startRow, pageSize);
      });
      presenter.queryGameTypeResult(mGameType, startRow, pageSize);
    }
  }

  @Override public void queryHistorySuccess(List<GameHistoryInfo> list) {
    if (startRow == 0) {
      mHistoryList.clear();
    }
    for (int i = 0; i < list.size(); i++) {
      GameHistoryInfo info = list.get(i);
      String issueId = info.getIssueId();
      String resultDate = info.getResultDate();
      String resultStr = info.getResultStr();
      if (resultDate.length() >= 12) {
        info.setDate(resultDate.substring(8, 10) + ":" + resultDate.substring(10, 12));
      }
      info.setIsSueId(
          issueId.length() >= 3 ? issueId.substring(issueId.length() - 3, issueId.length()) + "期"
              : issueId + "期");
      if (resultStr.length() > 0) {
        String[] str = resultStr.split(",");
        if (Constants.pkArr.contains(mGameType)) {
          if (str.length >= 10) {
            info.setStringStr(Arrays.asList(str));
          }
        } else {
          if (str.length >= 5) {
            info.setStringStr(Arrays.asList(str));
          }
        }
      }
    }
    mHistoryList.addAll(list);
    if (null != mPkAdapter) {
      mPkAdapter.notifyDataSetChanged();
    }
    if (null != m115Adapter) {
      m115Adapter.notifyDataSetChanged();
    }
    if (null != mAdapter) {
      mAdapter.notifyDataSetChanged();
    }
  }

  @OnClick({
      R.id.cb_choose_big, R.id.cb_choose_small, R.id.cb_choose_single, R.id.cb_choose_double
  })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.cb_choose_big:
        if (!isBig) {
          isBig = true;
          isSmall = false;
          mCbBig.setChecked(true);
          mCbSmall.setChecked(false);
        } else {
          isBig = false;
          isSmall = false;
          mCbBig.setChecked(false);
          mCbSmall.setChecked(false);
        }
        select();
        break;
      case R.id.cb_choose_small:
        if (!isSmall) {
          isSmall = true;
          isBig = false;
          mCbSmall.setChecked(true);
          mCbBig.setChecked(false);
        } else {
          isSmall = false;
          isBig = false;
          mCbSmall.setChecked(false);
          mCbBig.setChecked(false);
        }
        select();
        break;
      case R.id.cb_choose_single:
        if (!isSingle) {
          isSingle = true;
          isDouble = false;
          mCbSingle.setChecked(true);
          mCbDouble.setChecked(false);
        } else {
          isSingle = false;
          isDouble = false;
          mCbSingle.setChecked(false);
          mCbDouble.setChecked(false);
        }
        select();
        break;
      case R.id.cb_choose_double:
        if (!isDouble) {
          isDouble = true;
          isSingle = false;
          mCbDouble.setChecked(true);
          mCbSingle.setChecked(false);
        } else {
          isDouble = false;
          isSingle = false;
          mCbDouble.setChecked(false);
          mCbSingle.setChecked(false);
        }
        select();
        break;
    }
  }

  public void select() {
    items.clear();
    if (isBig) {
      if (isSingle) {
        if (Constants.lotteryArr.contains(mGameType)) {
          for (int i = 0; i < allItems.size(); i++) {
            int ball = Integer.parseInt(allItems.get(i));
            if (ball > 4 && ball % 2 != 0) {
              items.add(allItems.get(i));
            }
          }
        } else {
          for (int i = 0; i < allItems.size(); i++) {
            int ball = Integer.parseInt(allItems.get(i));
            if (ball > 5 && ball % 2 != 0) {
              items.add(allItems.get(i));
            }
          }
        }
      } else if (isDouble) {
        if (Constants.lotteryArr.contains(mGameType)) {
          for (int i = 0; i < allItems.size(); i++) {
            int ball = Integer.parseInt(allItems.get(i));
            if (ball > 4 && ball % 2 == 0) {
              items.add(allItems.get(i));
            }
          }
        } else {
          for (int i = 0; i < allItems.size(); i++) {
            int ball = Integer.parseInt(allItems.get(i));
            if (ball > 5 && ball % 2 == 0) {
              items.add(allItems.get(i));
            }
          }
        }
      } else {
        if (Constants.lotteryArr.contains(mGameType)) {
          for (int i = 0; i < allItems.size(); i++) {
            int ball = Integer.parseInt(allItems.get(i));
            if (ball > 4) {
              items.add(allItems.get(i));
            }
          }
        } else {
          for (int i = 0; i < allItems.size(); i++) {
            int ball = Integer.parseInt(allItems.get(i));
            if (ball > 5) {
              items.add(allItems.get(i));
            }
          }
        }
      }
    } else if (isSmall) {
      if (isSingle) {
        if (Constants.lotteryArr.contains(mGameType)) {
          for (int i = 0; i < allItems.size(); i++) {
            int ball = Integer.parseInt(allItems.get(i));
            if (ball < 5 && ball % 2 != 0) {
              items.add(allItems.get(i));
            }
          }
        } else {
          for (int i = 0; i < allItems.size(); i++) {
            int ball = Integer.parseInt(allItems.get(i));
            if (ball < 6 && ball % 2 != 0) {
              items.add(allItems.get(i));
            }
          }
        }
      } else if (isDouble) {
        if (Constants.lotteryArr.contains(mGameType)) {
          for (int i = 0; i < allItems.size(); i++) {
            int ball = Integer.parseInt(allItems.get(i));
            if (ball < 5 && ball % 2 == 0) {
              items.add(allItems.get(i));
            }
          }
        } else {
          for (int i = 0; i < allItems.size(); i++) {
            int ball = Integer.parseInt(allItems.get(i));
            if (ball < 6 && ball % 2 == 0) {
              items.add(allItems.get(i));
            }
          }
        }
      } else {
        if (Constants.lotteryArr.contains(mGameType)) {
          for (int i = 0; i < allItems.size(); i++) {
            int ball = Integer.parseInt(allItems.get(i));
            if (ball < 5) {
              items.add(allItems.get(i));
            }
          }
        } else {
          for (int i = 0; i < allItems.size(); i++) {
            int ball = Integer.parseInt(allItems.get(i));
            if (ball < 6) {
              items.add(allItems.get(i));
            }
          }
        }
      }
    } else if (isSingle) {
      for (int i = 0; i < allItems.size(); i++) {
        int ball = Integer.parseInt(allItems.get(i));
        if (ball % 2 != 0) {
          items.add(allItems.get(i));
        }
      }
    } else if (isDouble) {
      for (int i = 0; i < allItems.size(); i++) {
        int ball = Integer.parseInt(allItems.get(i));
        if (ball % 2 == 0) {
          items.add(allItems.get(i));
        }
      }
    } else {
      items.addAll(allItems);
    }
    for (int i = 0; i < mBallList.size(); i++) {
      mBallList.get(i).setSelect(false);
    }
    if (null != mPkAdapter) {
      mPkAdapter.setAlpha(items);
    }
    if (null != m115Adapter) {
      m115Adapter.setAlpha(items);
    }
    if (null != mAdapter) {
      mAdapter.setAlpha(items);
    }
    mBallChooseAdapter.notifyDataSetChanged();
  }

  /*
   * 刷新开奖结果结果
   * */
  @Subscribe(code = RxBusCode.REFRESH_CODE)
  public void refresh() {
    if (null == mActivity || mActivity.isFinishing()) {
      return;
    }
    presenter.queryGameTypeResult(mGameType, startRow, pageSize);
  }

  @Override public void onDestroy() {
    super.onDestroy();
    RxBus.get().unRegister(this);
  }
}
